package com.yay.rental.provider;

import com.yay.rental.io.DataHandler;
import com.yay.rental.provider.RentalContract.CategoriesColumns;
import com.yay.rental.provider.RentalContract.RentalColumns;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;


/**
 * Get Started!
 * @author team@getstarted.com.ua
 * 
 * Helper for managing {@link SQLiteDatabase} that stores data for
 * {@link RentalProvider}.
 */
public class RentalDatabase extends SQLiteOpenHelper {
    private static final String TAG = "RentalDatabase";
    private static final String DATABASE_NAME = "rental.db";

    // NOTE: carefully update onUpgrade() when bumping database versions to make
    // sure user data is saved.
    // released version: 1
    private static final int DATABASE_VERSION = 2;
    
    private DataHandler mDataHandler;
    private Context context;
	

    public interface Tables {
        String CATEGORIES = "categories";
        String RENTALS = "rentals";
    }

    public RentalDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + Tables.CATEGORIES + " ("
        		+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + CategoriesColumns.IDP + " INTEGER,"
                + CategoriesColumns.NAME + " TEXT)");
        
        db.execSQL("CREATE TABLE " + Tables.RENTALS + " ("
        		+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + RentalColumns.IDP + " INTEGER,"
                + RentalColumns.NAME + " TEXT,"
                + RentalColumns.PRICE + " TEXT,"
                + RentalColumns.ACCOMMODATIONS + " TEXT,"
                + RentalColumns.DESCRIPTION + " TEXT)");
    
        // Insert initial data
        mDataHandler = new DataHandler(context, db);
        
        mDataHandler.insertCategories();
        mDataHandler.insertRentals();
        
        db.execSQL("CREATE INDEX categories_idp_idx ON categories(idp)");
        db.execSQL("CREATE INDEX rentals_idp_idx ON rentals(idp)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion);

        if(oldVersion != DATABASE_VERSION) {
            db.execSQL("DROP TABLE IF EXISTS " + Tables.CATEGORIES);
            db.execSQL("DROP TABLE IF EXISTS " + Tables.RENTALS);

            db.execSQL("DROP INDEX IF EXISTS categories_idp_idx");
            db.execSQL("DROP INDEX IF EXISTS rentals_idp_idx");
            
            onCreate(db);
        }
    }
}
